package org.example.core.security.handler;

import com.alibaba.fastjson2.JSONObject;
import org.apache.catalina.manager.Constants;
import org.example.core.enums.ApiResult;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Description: 登陆失败处理器
 * Date: 2024/1/28 15:01
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset="+ Constants.CHARSET);

        response.setHeader("Access-control-Allow-Origin", response.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", response.getHeader("Access-Control-Request-Headers"));
        // 跨域发送一个option请求
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            response.setStatus(HttpStatus.OK.value());
        }
        response.getWriter().write(JSONObject.toJSONString(ApiResult.failure(exception.getMessage())));
    }
}
